<?php

namespace app\common\model;

use think\Model;

/**
 * 每日一题模型
 */
class DailyQuestion extends Model
{
    // 表名
    protected $name = 'daily_question';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [
        'difficulty_text',
        'status_text'
    ];

    /**
     * 获取难度文本
     */
    public function getDifficultyTextAttr($value, $data)
    {
        $status = [
            'easy' => '简单',
            'medium' => '中等', 
            'hard' => '困难'
        ];
        return isset($status[$data['difficulty']]) ? $status[$data['difficulty']] : '未知';
    }

    /**
     * 获取状态文本
     */
    public function getStatusTextAttr($value, $data)
    {
        $status = [0 => '禁用', 1 => '启用'];
        return isset($status[$data['status']]) ? $status[$data['status']] : '未知';
    }

    /**
     * 获取格式化的选项数组
     */
    public function getOptionsAttr($value, $data)
    {
        return [
            ['key' => 'A', 'text' => $data['option_a']],
            ['key' => 'B', 'text' => $data['option_b']],
            ['key' => 'C', 'text' => $data['option_c']],
            ['key' => 'D', 'text' => $data['option_d']]
        ];
    }

    /**
     * 获取随机题目
     */
    public static function getRandomQuestion()
    {
        return self::where('status', 1)
            ->where('delete_time', null)
            ->orderRaw('RAND()')
            ->find();
    }

    /**
     * 根据分类获取题目
     */
    public static function getQuestionsByCategory($category)
    {
        return self::where('category', $category)
            ->where('status', 1)
            ->where('delete_time', null)
            ->order('weigh desc, id desc')
            ->select();
    }

    /**
     * 根据难度获取题目
     */
    public static function getQuestionsByDifficulty($difficulty)
    {
        return self::where('difficulty', $difficulty)
            ->where('status', 1)
            ->where('delete_time', null)
            ->order('weigh desc, id desc')
            ->select();
    }
}